package com.powernode.impl;

import com.powernode.constant.AuthConstants;
import com.powernode.factory.LoginStrategyFactory;
import com.powernode.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * 认证流程
 * @Author: DongGuoZhen
 * @Date: 2025/09/11/16:24
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        获取请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
//        获取请求类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
//        if(AuthConstants.SYS_USER_LOGIN.equals(loginType)) {
////            后台管理系统
//        } else {
////            小程序
//        }
        if(!StringUtils.hasText(loginType)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
//        使用 工厂模式 & 策略模式
        LoginStrategy loginStrategy = loginStrategyFactory.getLoginStrategy(loginType);
        return loginStrategy.realLogin(username);
    }
}
